package cn.itcast.service.impl;

import cn.itcast.papper.SearchMapper;
import cn.itcast.pojo.ItemDoc;
import cn.itcast.pojo.PageResult;
import cn.itcast.pojo.RequestParams;
import cn.itcast.service.ISearchService;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.hmall.common.dto.Item;
import com.hmall.common.dto.PageDTO;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;


@Service
public class SearchService implements ISearchService {
    @Autowired
    private SearchService service;

    @Autowired
    private RestHighLevelClient client;

// /**
//     * 关键词搜索
//     * match
//     * @param params
//     * @return

    @Override
    public PageDTO<ItemDoc> search(RequestParams params) throws IOException {
        SearchRequest searchRequest = new SearchRequest("item");

//        使用bool查询
             buildBasicQuery(params,searchRequest);

//        设置查询条件

//        设置分页
        int index = (params.getPage()-1)*params.getSize();
        searchRequest.source().from(index);
        searchRequest.source().size(params.getSize());
//        设置排序
        String sortBy = params.getSortBy();
        if(sortBy.equals("sold")){
//              销量排序
            searchRequest.source().sort(sortBy, SortOrder.DESC);
        }else if(sortBy.equals("price")){
//            价格排序
            searchRequest.source().sort(sortBy, SortOrder.ASC);
        }

        try {
            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);

            SearchHits hits = response.getHits();

            long total = hits.getTotalHits().value;
            List<ItemDoc> list = new ArrayList<>();
            for (SearchHit hit : hits) {
                String jsonStr = hit.getSourceAsString();
//                把json转对象
                ItemDoc itemDoc = JSON.parseObject(jsonStr, ItemDoc.class);
                list.add(itemDoc);
            }
            return new PageDTO<>(total,list);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    //自动补全
    @Override
    public List<String> getSuggestion(String key) {
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("item");
            // 2.准备DSL
            request.source().suggest(new SuggestBuilder().addSuggestion(
                    "suggestion",
                    SuggestBuilders.completionSuggestion("suggestion")
                            .text(key)
                            .skipDuplicates(true)
                            .size(10)
            ));
            // 3.发起请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 4.解析结果
            Suggest suggest = response.getSuggest();
            // 4.1.根据补全查询名称，获取补全结果
            CompletionSuggestion suggestions = suggest.getSuggestion("suggestion");
            // 4.2.获取options
            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
            // 4.3.遍历
            List<String> list = new ArrayList<>(options.size());
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().toString();
                list.add(text);
            }
            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //过滤项聚合功能
    @Override
    public Map<String, List<String>> getFilters(RequestParams params) {
        try {
            //1.准备Request
            SearchRequest request = new SearchRequest("item");
            //2.准备DSL
            //query
        buildBasicQuery(params, request);
            //2.1设置size
            request.source().size(0);
            //2.2聚合
            buildAggregation(request);
            //3.发出请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
//4.解析结果
            HashMap<String, List<String>> result = new HashMap<>();
            Aggregations aggregations = response.getAggregations();
            //4.1根据品牌名称，获取
            List<String> brandList = getAggByName(aggregations, "brandAgg");
            result.put("brand", brandList);
            List<String> categoryList = getAggByName(aggregations, "categoryAgg");
            result.put("category", categoryList);

            return result;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //添加算分函数查询
    private void buildAggregation(SearchRequest request) {
        request.source().aggregation(AggregationBuilders
                .terms("categoryAgg")
                .field("category")
                .size(100));


        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(100));

    }
    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        //4.1根据聚合名称获取聚合结果
        Terms brandTerms = aggregations.get(aggName);
        //4.2获取buckets
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        //4.3遍历
        ArrayList<String> brandlist = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            //4.4获取key
            String key = bucket.getKeyAsString();
            brandlist.add(key);
        }
        return brandlist;
    }

    private void buildBasicQuery(RequestParams params, SearchRequest request) {
        // 1.构建BooleanQuery
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 关键字搜索
        String key = params.getKey();
        if (key == null || "".equals(key)) {
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        }
        // 分类
        if (params.getCategory() != null && !params.getCategory().equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("category", params.getCategory()));
        }
        // 品牌条件
        if (params.getBrand() != null && !params.getBrand().equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        // 价格
        if (params.getMinPrice() != null && params.getMaxPrice() != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price").gt(params.getMinPrice()*100).lt(params.getMaxPrice()*100));

        }
        // 2.算分控制
        FunctionScoreQueryBuilder functionScoreQuery =
                QueryBuilders.functionScoreQuery(
                        // 原始查询，相关性算分的查询
                        boolQuery,
                        // function score的数组
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                // 其中的一个function score 元素
                                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                        // 过滤条件
                                        QueryBuilders.termQuery("isAD", true),
                                        // 算分函数
                                        ScoreFunctionBuilders.weightFactorFunction(10)
                                )
                        });
        request.source().query(functionScoreQuery);
    }
}

